package jobs

import (
	"github.com/go-admin-team/go-admin-core/logger"
	"github.com/go-admin-team/go-admin-core/sdk"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"go-admin/app/hunter/models"
	"gorm.io/gorm"
	"time"
)

// InitJob
// 需要将定义的struct 添加到字典中；
// 字典 key 可以配置到 自动任务 调用目标 中；
func InitJob() {
	jobList = map[string]JobExec{
		"ExamplesOne": ExamplesOne{},
		// ...
	}
}

// ExamplesOne
// 新添加的job 必须按照以下格式定义，并实现Exec函数
type ExamplesOne struct {
	api.Api
}

func (t ExamplesOne) Exec(arg interface{}) error {
	log := logger.NewHelper(sdk.Runtime.GetLogger())
	db := sdk.Runtime.GetDbByKey("localhost:8080")
	var c models.HtContract
	var list []models.HtContract
	beginTime := time.Now()
	endTime := beginTime.Add(time.Minute * 30)
	// 提前30分钟通知钉钉或者飞书，通知cd为5分钟
	afterUpdate := beginTime.Add(-time.Minute * 5)
	db.Model(&c).Scopes(func(db *gorm.DB) *gorm.DB {
		db.Where("ht_contract.notify_time > ? and ht_contract.notify_time < ?", beginTime, endTime)
		db.Where("ht_contract.updated_at > ?", afterUpdate)
		return db
	}).Find(&list)
	log.Info("notify count: ", len(list))
	for _, contract := range list {
		db.Model(c.TableName()).Update("update_at", beginTime).Where("id = ?", contract)
	}

	//notify.Send()

	return nil
}
